package cn.codesea.housework_user.ui.worker;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.codesea.housework_user.R;
import cn.codesea.housework_user.adapter.listener.OnRecyclerItemClickServiceListener;
import cn.codesea.housework_user.adapter.WorkerMySerListRcvAdapter;
import cn.codesea.housework_user.entity.Service;
import cn.codesea.housework_user.entity.ServiceVO;
import cn.codesea.housework_user.entity.Worker;
import cn.codesea.housework_user.net.ServiceGenerator;
import cn.codesea.housework_user.net.data.Result;
import cn.codesea.housework_user.net.service.WorkerService;
import cn.codesea.housework_user.ui.GuideActivity;
import cn.codesea.housework_user.utils.SPUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Tab2MineFragment extends Fragment {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.modify_tv)
    TextView modify_tv;
    WorkerMySerListRcvAdapter adapter;
    private LinearLayoutManager mLinearLayoutManager;

    @BindView(R.id.logout_tv)
    TextView logout_tv;

    Worker worker;

    @BindView(R.id.name_tv)
    TextView name_tv;

    List<Service> services = new ArrayList<>();

    @BindView(R.id.service_tv)
    TextView service_tv;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab2_mine_worker,container,false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }

    private void init(){
        initData();
        initView();
    }

    private void initData() {
        worker = SPUtil.getWorker(getActivity());
//        updateRecyclerView();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            updateRecyclerView();
        }
    }

    public void updateRecyclerView(){
        WorkerService service = ServiceGenerator.createService(WorkerService.class);
        Call<Result> call = service.getWorkerServices(worker.getWorkerid());
        call.enqueue(new Callback<Result>(){
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                resultProcess(response.body());
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
//                Toast.makeText(getActivity(),"网络错误!",Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void initView(){

        adapter = new WorkerMySerListRcvAdapter(getActivity(),services);
        adapter.setRecyclerItemClickListener(new OnRecyclerItemClickServiceListener() {
            @Override
            public void onItemClick(int Position, List<Service> list) {
//                Toast.makeText(getActivity(),Position+"查看:" +list.get(Position), Toast.LENGTH_SHORT).show();
//                startActivity(new Intent(getActivity(),MineOldActivity.class));
            }
        });
        mLinearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(adapter);

        name_tv.setText(worker.getName());

    }

    @OnClick(R.id.modify_tv)
    public void modify_tv(){
//        Toast.makeText(getActivity(),"编辑", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(getActivity(),RegisterWorkerActivity.class).putExtra("type","update"));
    }

    @OnClick(R.id.logout_tv)
    public void logout_tv(){
        SPUtil.logout(getActivity());
        startActivity(new Intent(getActivity(),GuideActivity.class));
        getActivity().finish();
    }

    /**
     * 结果处理
     */
    public void resultProcess(Result result){
        if (result.getState() == 200){

            Type type = new TypeToken<List<Service>>(){}.getType();
            List<Service> sers = new Gson().fromJson(String.valueOf(result.getRes()),type);
            List<ServiceVO> ms = new ArrayList<>();
            for (Service s : sers){
                if (s.getPid() == 0){
                    ServiceVO sVO = new ServiceVO();
                    sVO.setId(s.getId());
                    sVO.setPid(s.getPid());
                    sVO.setName(s.getName());
                    sVO.setDesc(s.getDesc());
                    sVO.setMark(s.getMark());
                    List<Service> services = new ArrayList<>();
                    sVO.setServices(services);
                    ms.add(sVO);
                }
            }
            for (Service s : sers){
                if (s.getPid() != 0){
                    for (ServiceVO sVO : ms){
                        if (s.getPid() == sVO.getId()){
                            sVO.getServices().add(s);
                            break;
                        }
                    }
                }
            }

            // 这里默认 只能选择一个服务大类，以及 该大类下的几个小类。后期可以扩展为，选择多个大类。
            this.services.clear();
            this.services.addAll(ms.get(0).getServices());
            adapter.notifyDataSetChanged();

            service_tv.setText(ms.get(0).getName());

        }else {
            Toast.makeText(getActivity(),"网络错误！",Toast.LENGTH_SHORT).show();
        }
    }
}
